package com.i_art_engineer.meigong.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;

import com.i_art_engineer.meigong.AppConsts;
import com.i_art_engineer.meigong.AppContext;
import com.i_art_engineer.meigong.AppHttpClient;
import com.i_art_engineer.meigong.R;
import com.i_art_engineer.meigong.base.FullScreenActivity;
import com.i_art_engineer.meigong.gallery.GalleryView;
import com.i_art_engineer.meigong.adapter.FlowAdAdapter;
import com.i_art_engineer.meigong.widget.AlertDialog;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.squareup.picasso.Picasso;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

import cz.msebera.android.httpclient.Header;
import cz.msebera.android.httpclient.impl.client.SystemDefaultCredentialsProvider;

/**
 *
 */
public class MainActivity extends FullScreenActivity {

    private ImageButton ib_photo, ib_account, ib_works, ib_watermark;
    private GalleryView gallery;
    private FlowAdAdapter adapter;

    private ImageView ll_banner;

    // 点击事件
    View.OnClickListener listener = new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            switch (arg0.getId()) {

                case R.id.ib_photo:
                    Intent intent = new Intent(MainActivity.this, PhotoSelectorActivity.class);
                    // 是否显示拍摄图片
                    intent.putExtra(PhotoSelectorActivity.EXTRA_SHOW_CAMERA, true);
                    // 最大可选择图片数量
                    intent.putExtra(PhotoSelectorActivity.EXTRA_SELECT_COUNT, AppConsts.PHOTO_SELECTOR_IMAGE_MAX_NUM);
                    // 选择模式
                    intent.putExtra(PhotoSelectorActivity.EXTRA_SELECT_MODE, PhotoSelectorActivity.MODE_MULTI);
//                    startActivityForResult(intent, AppConsts.ACTIVITY_REQUEST_PHOTO_SELECTOR_IMAGE);
                    startActivityForResult(intent, AppConsts.ACTIVITY_REQUEST_PHOTO_SELECTOR_IMAGE);
                    break;

                case R.id.ib_account:
                    //显示个人中心界面
                    startActivity(new Intent(MainActivity.this, AccountActivity.class));
                    break;

                case R.id.ib_works:
                    //显示作品欣赏界面
                    startActivity(new Intent(MainActivity.this, WorksActivity.class));
                    break;

                case R.id.ib_watermark:
                    Log.i("watermark", AppContext.getTicket());
                    AsyncHttpResponseHandler handler = new JsonHttpResponseHandler() {
                        @Override
                        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                            try {
                                Log.i("watermark", response.toString());
                                int code = response.getInt("code");
                                String msg = response.getString("msg");
                                msg = msg.replaceAll("\\\\n", "\n");
                                Log.i("watermark-msg", msg);
                                if (code == 200) {
                                    Intent intent = new Intent(MainActivity.this, PhotoSelectorActivity.class);
                                    // 是否显示拍摄图片
                                    intent.putExtra(PhotoSelectorActivity.EXTRA_SHOW_CAMERA, true);
                                    // 最大可选择图片数量
                                    intent.putExtra(PhotoSelectorActivity.EXTRA_SELECT_COUNT, AppConsts.PHOTO_SELECTOR_IMAGE_MAX_NUM);
                                    // 选择模式
                                    intent.putExtra(PhotoSelectorActivity.EXTRA_SELECT_MODE, PhotoSelectorActivity.MODE_MULTI);
//                                    startActivityForResult(intent, AppConsts.ACTIVITY_REQUEST_PHOTO_SELECTOR_IMAGE);
                                    startActivity(intent);
                                } else if (code == 204) {
                                    //显示水印提示信息
                                    if (msg == null || TextUtils.isEmpty(msg)) {
                                        msg = getString(R.string.water_mark_hint);
                                    }

                                    new AlertDialog(MainActivity.this).builder().setTitle(getString(R.string.dlg_title_hint)).setMsg
                                            (msg).setPositiveButton(getString(R.string.btn_ok),
                                            new View.OnClickListener() {
                                                @Override
                                                public void onClick(View v) {

                                                }
                                            }).setNegativeButton(getString(R.string.btn_cancel), new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {

                                        }
                                    }).show();
                                }
                            } catch (JSONException e) {
                            }

                        }

                        @Override
                        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                            Log.i("watermark", responseString);
                        }
                    };
                    AppHttpClient.post(AppConsts.API_PROFILE_HINT, handler);

                    break;
                case R.id.ll_banner:
                    AdInfo ad = (AdInfo) ll_banner.getTag();
                    switch (ad.getType()) {
                        case 1:
                            openWebView(ad.getUri());
                            break;
                        case 2: //长图
                            openWebView(ad.getUri());
                            break;
                        case 3:
                            openWorksByGroup(ad.getUri());
                            break;
                    }
                    break;
            }
        }
    };

    public void openWorksByGroup(String id) {
        Intent intent = new Intent(MainActivity.this, WorksActivity.class);
        intent.putExtra("group_id", id);
        startActivity(intent);
    }

    public void openWebView(String url) {
        Intent intent = new Intent(MainActivity.this, WebViewActivity.class);
        intent.putExtra(WebViewActivity.EXTRA_WEB_URL, url);
        startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initGalleryView();
        initMenuBar();
        initAdBanner();

    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    protected void onRestart() {
        super.onRestart();
        String token = AppContext.getTicket();
        if (token == null) {
            finish();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);


        if (requestCode == AppConsts.ACTIVITY_REQUEST_PHOTO_SELECTOR_IMAGE) {
            if (resultCode == RESULT_OK) {
                //弹出图片编辑界面
                ArrayList<String> mSelectPath = data.getStringArrayListExtra(PhotoSelectorActivity.EXTRA_RESULT);
                Intent intent = new Intent(MainActivity.this, PhotoEditorActivity.class);
                intent.putStringArrayListExtra(PhotoEditorActivity.EXTRA_SELECTED_IMAGES, mSelectPath);
                startActivity(intent);
                is_can_free=true;
                is_can_scrool=false;
            }
        }
    }

    private void initGalleryView() {
//        if(gallery==null)
        {
            gallery = (GalleryView) findViewById(R.id.mygallery);
            long start= System.currentTimeMillis();
            adapter = new FlowAdAdapter(this);
            long end=System.currentTimeMillis();
            Log.e("mainactivity","adapter="+(end-start));
            gallery.setAdapter(adapter);
            gallery.setSelection(adapter.getCount() / 2);
            gallery.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                }

                @Override
                public void onNothingSelected(AdapterView<?> parent) {
                }
            });

            gallery.setOnItemClickListener(new AdapterView.OnItemClickListener() {            // 设置点击事件监听
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    //根据不同的类型使用不同的打开方式
                    AdInfo ad = (AdInfo) view.getTag();
                    switch (ad.getType()) {
                        case 1:
                            openWebView(ad.getUri());
                            break;
                        case 2: //长图
                            openWebView(ad.getUri());
                            break;
                        case 3:
                            openWorksByGroup(ad.getUri());
                            break;
                    }
                }
            });
            if(urls.size()==0)
              loadAdFlow();
//            mHandler.sendEmptyMessage(CHANGE_BANNER);
            startAutoScroll();
        }
    }
    ArrayList<String> urls = new ArrayList<>();
    ArrayList<AdInfo> data = new ArrayList<>();// 广告列表
    private void loadAdFlow() {
        AsyncHttpResponseHandler handler = new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                Log.d("initAd", response.toString());
                try {
                    int code = response.getInt("code");
                    if (code == 200) {

                        JSONArray jarr = response.getJSONArray("data");
                        for (int i = 0; i < jarr.length(); i++) {
                            JSONObject jobj = jarr.getJSONObject(i);
                            String imgurl = jobj.getString("img_url");
                            String dst_uri = jobj.getString("dst_uri");
                            int dst_type = jobj.getInt("dst_type");
                            AdInfo ad = new AdInfo(dst_type, dst_uri);
                            urls.add(imgurl);
                            data.add(ad);
                        }
                        adapter.buildViews(urls, data);
                        adapter.notifyDataSetChanged();

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                super.onFailure(statusCode, headers, throwable, errorResponse);
                Toast.makeText(MainActivity.this,"连接服务器超时",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {

            }
        };
        AppHttpClient.post(AppConsts.API_AD_FLOW, handler);
    }

    private void initMenuBar() {
        ib_photo = (ImageButton) findViewById(R.id.ib_photo);
        ib_photo.setOnClickListener(listener);
        ib_account = (ImageButton) findViewById(R.id.ib_account);
        ib_account.setOnClickListener(listener);
        ib_works = (ImageButton) findViewById(R.id.ib_works);
        ib_works.setOnClickListener(listener);
        ib_watermark = (ImageButton) findViewById(R.id.ib_watermark);
        ib_watermark.setOnClickListener(listener);
    }

    private void initAdBanner() {
        ll_banner = (ImageView) findViewById(R.id.ll_banner);
        ll_banner.setOnClickListener(listener);
        loadAdBanner();
    }

    private void loadAdBanner() {
        AsyncHttpResponseHandler handler = new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                Log.d("loadAdBanner", response.toString());
                try {
                    int code = response.getInt("code");
                    String msg = response.getString("msg");
                    if (code == 200) {
                        JSONArray jarr = response.getJSONArray("data");
                        if (jarr.length() > 0) {
                            JSONObject jdata = jarr.getJSONObject(0);
                            String img_url = jdata.getString("img_url");
                            String dst_uri = jdata.getString("dst_uri");
                            int dst_type = jdata.getInt("dst_type");
                            AdInfo ad = new AdInfo(dst_type, dst_uri);
                            ll_banner.setTag(ad);
                            Picasso.with(MainActivity.this)
                                    .load(img_url)
                                    .resize(ll_banner.getWidth(), ll_banner.getHeight())
                                    .noFade()
                                    .into(ll_banner);
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                super.onFailure(statusCode, headers, throwable, errorResponse);
                Toast.makeText(MainActivity.this,"连接服务器超时",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {

            }
        };
        AppHttpClient.post(AppConsts.API_AD_BANNER, handler);
    }
    public static boolean is_can_free=false;
    @Override
    protected void onStop() {
        super.onStop();
//        if(is_can_free)
//             adapter.FreeBitmap();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

    public class AdInfo {

        String mDstUri;
        int mDstType;

        public AdInfo(int dstType, String dstUri) {
            this.mDstUri = dstUri;
            this.mDstType = dstType;
        }

        public String getUri() {
            return mDstUri;
        }

        public int getType() {
            return mDstType;
        }
    }
    public  static boolean is_can_scrool=true;
    private void startAutoScroll() {
        new Thread() {
            @Override
            public void run() {
                while (is_can_scrool) {

                    mHandler.sendEmptyMessage(CHANGE_BANNER);

                    try {

                        Thread.sleep(5000);

                    } catch (InterruptedException e) {

                        e.printStackTrace();
                    }
                }
            }
        }.start();
    }

    public Handler mHandler= new Handler() {
        @Override
        public void handleMessage(Message msg) {
        switch (msg.what) {
            case CHANGE_BANNER:
                if(gallery.getAdapter().getCount()>0)
                     gallery.onKeyDown(KeyEvent.KEYCODE_DPAD_RIGHT, null);
                break;
        }
        }
    };
    public static final  int CHANGE_BANNER = 1001;
    public int mPosition=0;
    public boolean mOnTouch=false;
    public boolean mAutoScroll=true;

}
